<?php
/**
 * This file is part of EasySwoole.
 *
 * @link https://www.easyswoole.com
 * @document https://www.easyswoole.com
 * @contact https://www.easyswoole.com/Preface/contact.html
 * @license https://github.com/easy-swoole/easyswoole/blob/3.x/LICENSE
 */

namespace App\HttpController\Api;

use EasySwoole\AtomicLimit\AtomicLimit;
use EasySwoole\Component\Di;
use EasySwoole\Http\AbstractInterface\Controller;

class Index extends Controller
{
    /** @var AtomicLimit $autoLimiter */
    private $autoLimiter;

    protected function onRequest(?string $action): ?bool
    {
        $this->autoLimiter = Di::getInstance()->get('auto_limiter');

        if ($action == 'test1') {
            # 调用限流器对 http://127.0.0.1:9501/test1 请求限制流量
            if ($this->autoLimiter->access($action, 1)) {
                return true;
            } else {
                $this->writeJson(200, null, 'test1 refuse!');
                return false;
            }
        } else if ($action == 'test2') {
            # 调用限流器对 http://127.0.0.1:9501/test2 请求限制流量
            if ($this->autoLimiter->access($action, 2)) {
                return true;
            } else {
                $this->writeJson(200, null, 'test2 refuse!');
                return false;
            }
        }

        return parent::onRequest($action);
    }

    public function test1()
    {
        $this->writeJson(200, null, 'test1 success!');
    }

    public function test2()
    {
        $this->writeJson(200, null, 'test2 success!');
    }
}